package com.hefan.api.controller.comment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.hefan.api.service.comment.CommentsLocalService;
import com.hefan.club.comment.bean.Comments;
import com.hefan.club.dynamic.bean.Message;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import com.hefan.oms.bean.Present;
import com.hefan.user.bean.WebUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/v1/comments")
public class CommentsController {


    public static Logger logger = LoggerFactory.getLogger(CommentsController.class);

    @Resource
    CommentsLocalService commentsLocalService;

    /**
     * 获取动态下全部评论信息（分页）
     *
     * @throws
     * @Title: getComments
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param: @param request
     * @param: @return
     * @return: String
     * @author: LiTeng
     * @date: 2016年9月27日 下午4:55:48
     */
    @RequestMapping("/getComments")
    @ResponseBody
    public String getMessageComments(HttpServletRequest request) {
        ResultBean res = new ResultBean();
        Page page = new Page();
        try {
            //接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            int messageId = MapUtils.getIntValue(paramMap, "messageId", -1);
            page.pageNo = MapUtils.getIntValue(paramMap, "pageNo", page.pageNo);
            page.pageSize = MapUtils.getIntValue(paramMap, "pageSize", page.pageSize);
            if (messageId < 0) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            Map map = commentsLocalService.getMessageComments(messageId, page);
            res.setCode(ResultCode.SUCCESS.get_code());
            res.setData(map);
            return JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            res.setCode(ResultCode.UNSUCCESS.get_code());
            Map<String, Integer> coMap = new HashMap<String, Integer>();
            coMap.put("commentsCount", 0);
            coMap.put("presentCount", 0);
            coMap.put("praiseCount", 0);
            Map resMap = new HashMap();
            resMap.put("commentsPage", page);
            resMap.put("countMs", coMap);
            res.setData(resMap);
            return JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect);
        }
    }

    /**
     * 消息【获取消息列表内“评论”内容】
     *
     * @throws
     * @Title: getCommentsForMe
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param: @param request
     * @param: @return
     * @return: String
     * @author: LiTeng
     * @date: 2016年9月27日 下午6:03:44
     */
    @RequestMapping("/getCommentsForMe")
    @ResponseBody
    public String getCommentsForMe(HttpServletRequest request) {
        ResultBean res = new ResultBean();
        Page page = new Page();
        try {
            //接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            String userId = MapUtils.getStrValue(paramMap, "userId", "-1");
            page.pageNo = MapUtils.getIntValue(paramMap, "pageNo", page.pageNo);
            page.pageSize = MapUtils.getIntValue(paramMap, "pageSize", page.pageSize);
            page = commentsLocalService.getCommentsForMeByType(userId, 1, page);
            if (StringUtils.isBlank(userId)) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            res.setCode(ResultCode.SUCCESS.get_code());
            res.setData(page);
            return JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            res.setCode(ResultCode.UNSUCCESS.get_code());
            res.setData(page);
            return JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect);
        }
    }

    /**
     * 消息【获取消息列表内“礼物消息”内容】
     *
     * @throws
     * @Title: getGiftCommentsForMe
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param: @param request
     * @param: @return
     * @return: String
     * @author: LiTeng
     * @date: 2016年9月27日 下午6:04:55
     */
    @RequestMapping("/getGiftCommentsForMe")
    @ResponseBody
    public String getGiftCommentsForMe(HttpServletRequest request) {
        ResultBean res = new ResultBean();
        Page page = new Page();
        try {
            //接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            String userId = MapUtils.getStrValue(paramMap, "userId", "-1");
            page.pageNo = MapUtils.getIntValue(paramMap, "pageNo", page.pageNo);
            page.pageSize = MapUtils.getIntValue(paramMap, "pageSize", page.pageSize);
            if (StringUtils.isBlank(userId)) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            page = commentsLocalService.getCommentsForMeByType(userId, 2, page);
            res.setCode(ResultCode.SUCCESS.get_code());
            res.setData(page);
            return JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            res.setCode(ResultCode.UNSUCCESS.get_code());
            res.setData(page);
            return JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect);
        }
    }

    /**
     * 删除评论/回复
     *
     * @throws
     * @Title: deleteCommentsById
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param: @param request
     * @param: @return
     * @return: String
     * @author: LiTeng
     * @date: 2016年9月29日 上午11:46:30
     */
    @RequestMapping("/deleteComments")
    @ResponseBody
    public String deleteCommentsById(HttpServletRequest request) {
        ResultBean res = new ResultBean();
        try {
            //接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            if (null == paramMap || paramMap.isEmpty()) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            Long commentsId = MapUtils.getLongValue(paramMap, "commentsId", 0L);
            if (commentsId == null || commentsId < 0) {
                //非法参数
                return JSON.toJSONString(res = new ResultBean(ResultCode.ParamException.get_code(), "参数验证失败"));
            }
            Comments comm = this.commentsLocalService.getCommentsByIdForCheck(commentsId);
            if (comm == null || comm.getId() == null || comm.getId() < 0) {
                //获取平路失败
                return JSON.toJSONString(res = new ResultBean(ResultCode.ParamException.get_code(), "获取评论失败"));
            }
            Message mesInfo = this.commentsLocalService.getMessageInfoByIdForCheck(comm.getMessageId(), comm.getUserId());
            if (mesInfo == null || mesInfo.getMessageId() < 0) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("动态信息获取失败");
                return JSON.toJSONString(res);
            }
            String userId = HttpUtils.getParam(request, "consume", "");
            if (!userId.equals(comm.getUserId()) && !userId.equals(mesInfo.getUserId())) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("只有本人或动态创建人能删除评论");
                return JSON.toJSONString(res);
            }
            boolean isPresent = false;
            if (comm.getPresentId() != null && comm.getPresentId() > 0) {
//				//礼物评论不能删除
//				return JSON.toJSONString(res = new ResultBean(ResultCode.ParamException.get_code(),"礼物评论不能被删除"));
                isPresent = true;
            }
            res = this.commentsLocalService.deleteCommentsById(comm.getId(), comm.getMessageId(), isPresent, userId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            res.setCode(ResultCode.UNSUCCESS.get_code());
            res.setMsg("删除失败");
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 添加评论
     *
     * @param request
     * @return
     * @throws
     * @Title: addComment
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @return: String
     * @author: LiTeng
     * @date: 2016年10月9日 上午11:24:00
     */
    @RequestMapping("/addComment")
    @ResponseBody
    public String addComment(HttpServletRequest request) {
        ResultBean res = new ResultBean();
        try {
            //接参
            Comments comParam = HttpUtils.initParam(request, Comments.class);
            if (null == comParam) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            if (comParam == null || StringUtils.isBlank(comParam.getUserId())) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg(ResultCode.ParamException.getMsg());
                return JSON.toJSONString(res);
            }
            String userId = HttpUtils.getParam(request, "consume", "");
            if (!userId.equals(comParam.getUserId())) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("评论身份验证失败");
                return JSON.toJSONString(res);
            }
            WebUser user = this.commentsLocalService.getWebUserInfoById(userId);
            if (user == null || user.getId() <= 0) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("评论用户获取失败");
                return JSON.toJSONString(res);
            }
            if (comParam.getMessageId() == null) {
                comParam.setMessageId(0);
            }
            if (StringUtils.isBlank(comParam.getMuserId()) || comParam.getMessageId() <= 0) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("验证动态信息失败");
                return JSON.toJSONString(res);
            }
            Message mesInfo = this.commentsLocalService.getMessageInfoByIdForCheck(comParam.getMessageId(), userId);
            if (mesInfo == null || mesInfo.getMessageId() < 0) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("动态信息获取失败");
                return JSON.toJSONString(res);
            }
            if (comParam.getParentCommentsId() == null) {
                comParam.setParentCommentsId(0);
            }
            if (StringUtils.isBlank(comParam.getParentUserId())) {
                comParam.setParentUserId("");
            }
            if (comParam.getParentCommentsId() > 0) {
                if (StringUtils.isBlank(comParam.getParentUserId())) {
                    res.setCode(ResultCode.ParamException.get_code());
                    res.setMsg("验证评论信息失败");
                    return JSON.toJSONString(res);
                }
                Comments commCek = this.commentsLocalService.getCommentsByIdForCheck(comParam.getParentCommentsId());
                if (commCek == null || commCek.getId() == null || commCek.getId() < 0) {
                    //获取平路失败
                    return JSON.toJSONString(res = new ResultBean(ResultCode.ParamException.get_code(), "获取被回复的评论失败"));
                }
            }
            if ((comParam.getPresentId() == null || comParam.getPresentId() <= 0)
                    && StringUtils.isBlank(comParam.getCommentsInfo())) {
                res.setCode(ResultCode.ParamException.get_code());
                res.setMsg("普通评论内容不能为空");
                return JSON.toJSONString(res);
            }
            if (comParam.getPresentId() != null && comParam.getPresentId() > 0) {
                //礼物消息处理
                Present ps = this.commentsLocalService.getPresentById(Long.parseLong(comParam.getPresentId().toString()));
                if (ps == null || ps.getId() == null || ps.getId() <= 0) {
                    res.setCode(ResultCode.ParamException.get_code());
                    res.setMsg("礼物获取失败");
                    return JSON.toJSONString(res);
                }
                if (user.getBalance() < ps.getPrice()) {
                    res.setCode(ResultCode.RebalanceBalanceNotEnough.get_code());
                    res.setMsg(ResultCode.RebalanceBalanceNotEnough.getMsg());
                    return JSON.toJSONString(res);
                }
            }
            if (StringUtils.isBlank(comParam.getCommentsInfo())) {
                comParam.setCommentsInfo("");
            }
            comParam.setCommentsInfostatus("0");
            comParam.setCommentsTime(new Date());
            res = this.commentsLocalService.saveCommentsInfo(comParam);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            res.setCode(ResultCode.UNSUCCESS.get_code());
            res.setMsg("添加失败");
            return JSON.toJSONString(res);
        }
        return JSON.toJSONString(res);
    }
}
